package com.hna.cums.web.AnlyCtl;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.spark.SparkConf;
import org.apache.spark.deploy.ClientArguments;
//import org.apache.spark.deploy.yarn.Client;
import org.apache.spark.launcher.SparkLauncher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;

@Controller
public class AnlyMainCtl {

	/** 日志 */
	static final Logger logger = LoggerFactory.getLogger(AnlyMainCtl.class);
	private String sessionid;
	JSONObject resultObj = new JSONObject();

	@RequestMapping("AnlyTest.do")
	public String AnlyTest(HttpServletRequest request, HttpServletResponse response) {
		logger.info("Spark Lanncher start");
		sessionid = request.getSession().getId();
		logger.debug("session" + sessionid + " begin run");
		SparkLauncher launcher = new SparkLauncher();
		launcher.setAppName("RunApp" + sessionid);
		launcher.setAppResource("BigDataTest-0.1.1.jar"); // 要启动的spark应用包
//		launcher.setMainClass("JavaNetworkWordCount");
		launcher.setMaster("yarn");
		launcher.addAppArgs("");
//		launcher.setConf(SparkLauncher.DRIVER_MEMORY, "10m");
//		launcher.setConf(SparkLauncher.EXECUTOR_MEMORY, "32m");
//		launcher.setConf(SparkLauncher.EXECUTOR_CORES, "1");
		try {
			Process process = launcher.launch();
			InputStream stdInput = process.getInputStream();
			InputStream errInput = process.getErrorStream();
			dumpInput(stdInput);
			dumpInput(errInput);
			process.waitFor();
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		return null;
	}

	@PostConstruct
	public void init() {
		logger.debug("I'm  init  method  using  @PostConstrut...." + sessionid);
	}

	@PreDestroy
	public void dostory() {
		logger.debug("I'm  destory method  using  @PreDestroy....." + sessionid);
	}

	private static void dumpInput(InputStream input) throws IOException {
		byte[] buff = new byte[1024];

		while (true) {
			int len = input.read(buff);

			if (len < 0) {
				break;
			}

			System.out.println(new String(buff, 0, len));
		}
	}

}
